package com.suxin.netty.remoting;

import java.util.Collection;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author Tang
 * @classname ResponseSynchronizationManager
 * @description [ 注册全局回调 ]
 * @date 2022/12/15 23:46
 */
public class ResponseSynchronizationManager {

    /**
     * 响应表
     */
    private static final HashMap<String, ResponseFuture> RESPONSE_TABLE = new HashMap<>(8);

    /**
     * registerResponseCallback
     * @param opaque
     * @param future
     */
    public static void registerResponseCallback(String opaque, ResponseFuture future){
        RESPONSE_TABLE.put(opaque, future);
    }

    public static void removeCallback(String opaque){
        RESPONSE_TABLE.remove(opaque);
    }

    public static ResponseFuture getCallback(String opaque){
        if (Objects.isNull(opaque)) {
            return null;
        }
        return RESPONSE_TABLE.get(opaque);
    }

    /**
     * removeResponseCallback
     */
    public static void removeResponseCallback() {
        Collection<ResponseFuture> responseFutures = RESPONSE_TABLE.values();
        for (ResponseFuture future : responseFutures) {
            // 超时了移除回调
            if (future.isTimeout()) {
                RESPONSE_TABLE.remove(future.getOpaque());
            }
        }
    }

    public static HashMap<String, ResponseFuture> getResponseTable() {
        return RESPONSE_TABLE;
    }
}
